<template>
  <a-card :bordered="false" >
    <div v-if="mod=='normal'">
      <a-form layout="horizontal">
      </a-form>
      <a-space class="operator">
        <a-button @click="addNew" type="primary">新建</a-button>
      </a-space>
      <standard-table
        rowKey="id"
        :loading='loading'
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        @clear="onClear"
        @change="onChange"
        :expanded-row-keys="expandedRowKeys"
        @onExpand="onExpand"
      >
        <div slot="name" slot-scope="{record}">
          <a-input v-if="record.mod == 'add'" placeholder="请输入部门名" v-model="record.name" />
          <span v-if="record.mod == 'normal'">{{record.name}}</span>
        </div>
        <div slot="orders" slot-scope="{record}">
          <a-input v-if="record.mod == 'add'" v-model="record.orders" />
          <span v-if="record.mod == 'normal'">{{record.orders}}</span>
        </div>
        <div slot="action" slot-scope="{record}">
          <div v-if="record.mod == 'add'">
            <a-popconfirm title="确定添加？" ok-text="添加" cancel-text="取消" @confirm='confirm_add(record.name,record.parent_id,record.orders)'>
              <a >
                <a-icon type="file-add" />完成
              </a>
            </a-popconfirm>
            <a style="margin-right: 8px" @click="quxiao(record.id,record.parent_id)">
              <a-icon type="delete"/>取消
            </a>
          </div>
          <div v-if="record.mod == 'normal'">
            <a style="margin-right: 8px" @click="add(record.id)" v-if="record.parent_id == 0">
              <a-icon type="file-add"/>添加
            </a>
            <a style="margin-right: 8px" @click="edit(record.id)">
              <a-icon type="edit"/>编辑
            </a>
            <a style="margin-right: 8px" @click="yuangon(record.id,record.parent_id)">
              <a-icon type="container"/>员工
            </a>
            <a-popconfirm title="确定删除？" ok-text="删除" cancel-text="取消" @confirm='deleteRecord(record.id)'>
              <a >
                <a-icon type="delete" />删除
              </a>
            </a-popconfirm>
          </div>
        </div>
      </standard-table>
    </div>

    <div v-if="mod=='add'||mod=='edit'">
      <bumenDetail :mod.sync="mod" :type="status" :id="detail_id" :bumenList='bumenList' />
    </div>

    <a-drawer
      title="部门员工"
      :closable="false"
      :visible="show_drawer"
      @close="drawerClose"
      width='70%'
    >
      <user :showGonNeng="!show_drawer" :tfirst="first" :tsecond="second" />
    </a-drawer>
  </a-card>
</template>

<script>
import StandardTable from '@/components/table/StandardTable'
import {groupSecond,group,delGroup,addGroup} from '@/api/modules/bumen'
import bumenDetail from './bumen_detail'
import user from '../device/user.vue'

const columns = [
  {
    title: 'ID',
    width:150,
    dataIndex: 'id'
  },
  {
    title: '部门名',
    dataIndex: 'name',
    width:300,
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '人数',
    dataIndex: 'num',
    width:100,
  },
  {
    title: '排序',
    dataIndex: 'orders',
    width:100,
    scopedSlots: { customRender: 'orders' }
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Bumen',
  components: {StandardTable,bumenDetail,user},
  data () {
    return {
      mod:'normal',
      groupData:[],

      advanced: true,
      columns: columns,
      dataSource: [],
      selectedRows: [],

      bumenList:[],

      count:0,
      page:1,
      limit:10,
      keyword:'',
      type:1,
      status:1,

      add_id:0,
      detail_id:0,
      lastId:0,
      expandedRowKeys:[],
      loading:false,

      show_drawer:false,
      first:0,
      second:0
    }
  },
  activated() {
    this.init()
  },
  methods: {
    init(){
      this.getPeijianData()
    },
    getPeijianData(){
      this.loading = true;
      // let params = {
      //   page:this.page,
      //   limit:this.limit,
      // }
      // 获取顶级部门
      groupSecond({parent_id:0}).then((res) => {
        this.bumenList = res.data
        group({}).then((e) => {
          this.groupData = JSON.parse(JSON.stringify(e.data)) 
          let arr = []
          for(let item of e.data){
            item.mod = 'normal'; //与新增（add）区别
            if(item.parent_id == 0){
              let children = e.data.filter(o=>o.parent_id == item.id)
              if(children.length > 0){
                item.children = children
              }
              arr.push(item)
            }
          }
          this.dataSource = arr
          //获取最大id
          e.data.sort((a,b)=>a.id-b.id)
          this.lastId = e.data[e.data.length-1].id
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
      // getRecordComputer(params).then((res) => {
      //   this.dataSource = res.data.data
      //   this.count = res.data.count
      //   this.loading = false;
      // });
    },
    confirm_add(name,parent_id,orders){
      const loading = this.$message.loading('操作中')
      let params = {
        name,
        parent_id,
        orders
      }
      addGroup(params).then(() => {
        loading()
        this.$message.success('新增成功')
        this.init()
      }).catch(()=>{
        loading()
      });
    },
    tagChange(id){
      this.type = id
      this.init()
    },
    yuangon(id,parent_id){
      if(parent_id == 0){
        this.first = id;
        this.second = 0
      }else{
        this.first = parent_id;
        this.second = id;
      }
      // console.log(this.first,this.second,id,parent_id)

      this.show_drawer = true
    },
    add(id){
      let dataSource = JSON.parse(JSON.stringify(this.dataSource)) 
      //每次只能加一个
      let o = this.groupData.find(e=>e.mod == 'add')
      if(o){
        return this.$message.warning('请先完成添加')
      }

      this.add_id = id;
      let f = dataSource.find(e=>e.id == id)
      let x = this.expandedRowKeys.find(e=>e==id)
      if(!x){
        this.expandedRowKeys.push(id)
      }
      f.children = f.children || [];
      f.children.unshift({
        id: this.lastId + 1,
        level: 2,
        name: "",
        orders: 0,
        parent_id: id,
        mod:'add'
      })
      this.groupData.unshift({
        id: this.lastId + 1,
        level: 2,
        name: "",
        orders: 0,
        parent_id: id,
        mod:'add'
      })
      this.dataSource = dataSource
      this.lastId++
    },
    quxiao(id,parent_id){
      let dataSource = JSON.parse(JSON.stringify(this.dataSource)) 
      let groupData = JSON.parse(JSON.stringify(this.groupData)) 
      let f = dataSource.find(e=>e.id == parent_id)
      let idx = f.children.findIndex(e=>e.id == id)
      let idx2 = groupData.findIndex(e=>e.id==id)
      f.children.splice(idx,1)
      if(f.children.length == 0){
        delete f.children
      }
      this.dataSource = dataSource
      groupData.splice(idx2,1)
      //重置lastId
      groupData.sort((a,b)=>a.id-b.id)
      this.groupData = groupData
      this.lastId = this.groupData[this.groupData.length-1].id
    },
    edit(id){
      this.detail_id = id
      this.mod = 'edit'
    },
    deleteRecord(id) {
      this.loading = true
      delGroup({id}).then(() => {
        this.$message.success('删除成功')
        this.init()
      }).catch(() => {
        this.loading = false;
      });
    },
    onExpand(bool, row){
      if (bool) {
        this.expandedRowKeys = [...this.expandedRowKeys, row.id]
      } else {
        const index = this.expandedRowKeys.findIndex((e) => e === row.id)
        const newArray = [...this.expandedRowKeys]
        newArray.splice(index, 1)
        this.expandedRowKeys = newArray
      }
    },
    statusChange(id){
      this.status = id
      this.init()
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    remove () {
      this.dataSource = this.dataSource.filter(item => this.selectedRows.findIndex(row => row.key === item.key) === -1)
      this.selectedRows = []
    },
    onClear() {
      this.$message.info('您清空了勾选的所有行')
    },
    onStatusTitleClick() {
      this.$message.info('你点击了状态栏表头')
    },
    onChange(e) {
      this.page = e.current
      this.init()
    },
    onSelectChange() {
      this.$message.info('选中行改变了')
    },
    drawerClose(){
      this.show_drawer = false;
    },
    addNew () {
      this.detail_id = 0
      this.mod = 'add'
    },
    handleMenuClick (e) {
      if (e.key === 'delete') {
        this.remove()
      }
    }
  },
  watch:{
    mod(e){
      if(e=='normal'){
        this.init()
      }
    }
  },
  filters:{
    getStatus(e){
      switch(e){
        case 1:case '1':
          return '入库'
        case 2:case '2':
          return '出库'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .search{
    margin-bottom: 34px;
  }
  .fold{
    width: calc(100% - 216px);
    display: inline-block
  }
  .operator{
    margin-bottom: 18px;
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>
